package com.example.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.reggie.mapper.AddressBookMapper;
import com.example.reggie.entity.AddressBook;
import com.example.reggie.service.AddressBookService;
import com.example.reggie.utils.BaseContext;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Override
    public AddressBook setDefault(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getId());
        addressBook.setIsDefault(1);
        LambdaUpdateWrapper<AddressBook> luw = new LambdaUpdateWrapper();
        luw.eq(AddressBook::getUserId,addressBook.getUserId());
        luw.set(AddressBook::getIsDefault,0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        update(luw);
        //SQL:update address_book set is_default = 1 where id = ?
        updateById(addressBook);
        return addressBook;
    }

    @Override
    public AddressBook getDefault() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getId());
        queryWrapper.eq(AddressBook::getIsDefault, 1);

        //SQL:select * from address_book where user_id = ? and is_default = 1
        AddressBook addressBook = getOne(queryWrapper);
        return addressBook;
    }

    @Override
    public List<AddressBook> listByUser(AddressBook addressBook) {
        //条件构造器
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        //SQL:select * from address_book where user_id = ? order by update_time desc
        return list(queryWrapper);
    }
}
